//
//  SearchViewController.m
//  iWeddingDirectory
//
//  Created by Tung Ngo on 5/30/12.
//  Copyright (c) 2012 Home. All rights reserved.
//

#import "SearchViewController.h"
#import "API.h"
#import "Post.h"
#import "PostViewController.h"

@implementation SearchViewController

@synthesize searchBar;
@synthesize posts;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"Search" image:[UIImage imageNamed:@"search.png"] tag:0];
        self.tabBarItem = item;
        [item release];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [posts release];
    [searchBar release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    posts = [[NSMutableArray alloc] initWithCapacity:0];
    
    searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 240, 44)];
    searchBar.tintColor = [UIColor blackColor];
    searchBar.delegate = self;
    self.navigationItem.titleView = searchBar;
    
    UIActivityIndicatorView *waitingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [waitingIndicator setHidesWhenStopped:YES];
    [waitingIndicator setCenter:CGPointMake(160, 181)];
    [waitingIndicator setTag:1000];
    [waitingIndicator setHidden:YES];
    [self.view addSubview:waitingIndicator];
    [waitingIndicator release];
    
    UIBarButtonItem *buttonSearch = [[UIBarButtonItem alloc] initWithTitle:@"Search" style:UIBarButtonItemStyleBordered target:self action:@selector(onButtonSearchClicked:)];
    self.navigationItem.rightBarButtonItem = buttonSearch;
    [buttonSearch release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.searchBar = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [posts count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    Post *post = [posts objectAtIndex:indexPath.row];
    cell.textLabel.text = post.title;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    PostViewController *vcPost = [[PostViewController alloc] init];
    Post *post = [posts objectAtIndex:indexPath.row];
    [vcPost setPost:post];
    [vcPost setPostType:REMOTE_POST];
    [self.navigationController pushViewController:vcPost animated:YES];
    [vcPost release];
}

#pragma mark - Search result delegate

- (void)onResultReceived:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kResultReceivedNotification object:nil];
    
    UIActivityIndicatorView *waitingIndicator = (UIActivityIndicatorView *)[self.view viewWithTag:1000];
    [waitingIndicator stopAnimating];
    
    NSDictionary *result = [notification userInfo];
    NSArray *_posts = [result objectForKey:@"posts"];
    [posts removeAllObjects];
    for (NSDictionary *_post in _posts) {
        Post *post = [[Post alloc] init];
        int postId = [[_post objectForKey:@"id"] intValue];
        NSString *title = [_post objectForKey:@"title"];
        post.postId = postId;
        post.title = title;
        [posts addObject:post];
        [post release];
    }
    [self.tableView reloadData];
}

#pragma mark - Search

- (void)search:(NSString *)text
{
    UIActivityIndicatorView *waitingIndicator = (UIActivityIndicatorView *)[self.view viewWithTag:1000];
    [waitingIndicator startAnimating];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResultReceived:) name:kResultReceivedNotification object:nil];
    API *api = [API sharedInstance];
    [api searchForText:text];
}

#pragma mark - Search bar delegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)theSearchBar
{
    [searchBar resignFirstResponder];
    NSString *text = searchBar.text;
    if (text != nil && text.length > 0) {
        [self search:text];
    }
}

#pragma mark - Button click handlers

- (void)onButtonSearchClicked:(id)sender
{
    [searchBar resignFirstResponder];
    NSString *text = searchBar.text;
    if (text != nil && text.length > 0) {
        [self search:text];
    }
}

@end
